<?php

namespace app\common\model\goods;


use app\common\library\Search;
use app\common\model\CategoryFrontend;
use think\Model;

class GoodsModel extends Model
{
    protected $name = 'goods';


    /**
     * 分页列表
     * @ApiMethod POST
     *
     * @param int $user_id
     * @param int $cate_id 分类
     * @param int $is_index 爆款推荐:0=否,1=是
     * @param string $sort_field none=无,all=综合(销量+浏览量),hot=热度(浏览量),price=价格
     * @param string $sort asc=正序,desc=倒序
     * @param string $search 搜索内容
     * @param int $page
     * @param int $limit
     */
    public function getPageList($params, $user_id, $page, $limit)
    {
        extract($params);

        try {
            $user = model('User')->get($user_id);
            $field = ['id','goods_name','desc','keywords','image','price','original_price','is_index','coupon_exchange_id'];
            $where = [
                'status' => 'up',
//                'goods_spec.status' => 1,
            ];
            $order = [
                'createtime' => 'desc',
                'weigh' => 'asc',
            ];
            // 分类筛选查询和前台类目绑定的后台类目
            if($cate_id > 0){
                $cate_ids = CategoryFrontend::get($cate_id);
                if($cate_ids){
                    $where['cate_id'] = ['in',$cate_ids->admin_cate_ids];
                }
            }
//            if($is_index == 1){
//                $where['is_index'] = $is_index;
//            }
            $where['is_index'] = $is_index;
            switch ($sort_field){
                case 'all':
                    $order = [
                        'views' => $sort,
                        'sales' => $sort,
                    ];
                    break;
                case 'hot':
                    $order = [
                        'sales' => $sort,
                    ];
                    break;
                case 'price':
                    $order = [
                        'price' => $sort,
                    ];
                    break;
            }
            if(!empty($search)){

//                $searchPackage = (new \app\common\library\Search)->searchPackage($search);
//                $where['keywords'] = ['like',$searchPackage];

//                $where['keywords'] = ['like',"%$search%"];

                $words = Search::getWord($search);

//                $where['keywords'] = array('or');
//                foreach ($words as $value) {
//                    array_unshift($where['keywords'], array('like', '%'.$value.'%'));
//                }
//                $field[] = 'LOCATE("'.$search.'",keywords) as gIndex';
//                $order['gIndex'] = 'desc';

                $where['goods_name'] = array('or');
                foreach ($words as $value) {
                    array_unshift($where['goods_name'], array('like', '%'.$value.'%'));
                }
                $field[] = 'LOCATE("'.$search.'",goods_name) as gIndex2';
                $order['gIndex2'] = 'desc';

                // 添加搜索记录
                if($user){
                    $GoodsSearchLog = GoodsSearchLogModel::get(['user_id' => $user_id,'title' => $search]);
                    if($GoodsSearchLog){
                        $GoodsSearchLog->delete();
                    }
                    GoodsSearchLogModel::addLog($user_id,$search);
//                    throw new \Exception('请登录',401);
                }

            }
            $list = $this
                ->field($field)
//                ->withSum(['spec' => function($query){
//                    $query->where('status',1);
//                    $query->whereNull('deletetime');
//                }],'spec_stock')
                ->with(['couponexchange'])
                ->where($where)
                ->whereNull('deletetime')
                ->order($order)
                ->paginate($limit, false, ['page' => $page]);

            $system = model('app\common\model\SystemModel')->get(1);

            foreach ($list as $row){
                $row->spec_sum = model('app\admin\model\goods\GoodsSpec')
                    ->where(['goods_id' => $row->id,'status' => 1])
                    ->whereNull('deletetime')
                    ->sum('spec_stock');
                // 是否可购买
                $row->isCanPay = true;
                if($system->is_burst_goods_buy_limit_user == 1) {
                    if($row->is_index == 1) {
                        $row->isCanPay = false;
                    }
                    if($user) {
                        if($user->group_id > 1) {
                            $row->isCanPay = false;
                        }else{
//                            if($user->pid > 0) {
//                                $row->isCanPay = true;
//                            }
                            $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $user_id]);
                            if($user_relation) {
                                if($user_relation->user_id_2 > 0) {
                                    $row->isCanPay = true;
                                }else{
                                    if($user_relation->user_id_3 > 0) {
                                        $row->isCanPay = true;
                                    }
                                }
                            }
                        }
                    }
                }
                $row->image = ImageAddDomain($row->image);
            }
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 详情
     * @ApiMethod POST
     *
     * @param int $user_id
     * @param int $goods_id
     *
     */
    public function getDetail($params,$user_id)
    {
        extract($params);

        try {
            $user = model('User')->get($user_id);
            $share_earnings = [];
            if($user) {
                $share_earnings = model('app\common\model\ShareEarningsModel')->get(['group_id' => $user->group_id]);
            }

            $field = ['id','goods_name','desc','image','images','price','original_price','params','content','limit_num','service_ids','is_index'];
            $where = [
                'id' => $goods_id,
                'status' => 'up',
            ];

            $data = $this
                ->field($field)
//                ->withSum(['spec' => function($query){
//                    $query->where('status',1);
//                    $query->whereNull('deletetime');
//                }],'spec_stock')
                ->with(['spec' => function($query){
                    $query->field('goods_spec_id,goods_id,goods_spec_sn,spec_item_key,spec_item_value,spec_price,spec_stock,spec_sold_count,spec_image,unit,weight');
                    $query->where('status',1);
                    $query->whereNull('deletetime');
                }])
                ->where($where)
                ->whereNull('deletetime')
                ->find();

            if(!$data){
                throw new \Exception('商品已下架',48101);
            }

            $data->spec_sum = model('app\admin\model\goods\GoodsSpec')
                ->where(['goods_id' => $data->id,'status' => 1])
                ->whereNull('deletetime')
                ->sum('spec_stock');

            $GoodsServiceName = GoodsService::whereIn('id',$data->service_ids)->column('name');
            $data->service_ids_text = implode('/',$GoodsServiceName);
            $data->service_ids_text_arr = $GoodsServiceName;

            $data->image = ImageAddDomain($data->image);
            $data->images = MoreImageDomain($data->images);
            $data->params = JsonDe($data->params);

            $spec_item_key = [];

            // 规格选项
            if($data->spec) {
                foreach ($data->spec as $row1) {
                    $row1->spec_image = ImageAddDomain($row1->spec_image);
                    // TODO 会员价格处理? 是否是分销时补价差?
//                    if($user && $share_earnings) {
//                        $row1->spec_price -= $share_earnings->differential;
//                    }
                    $spec_item_key[] = $row1->spec_item_key;
//                    $row1_spec_item_key = explode(',',$row1->spec_item_key);
//                    sort($row1_spec_item_key);
//                    $row1->spec_item_key = $row1_spec_item_key;
                }
            }
            $spec_item_key = array_unique( explode(',', implode(',',$spec_item_key) ) );
            $spec_item_key_ids = implode(',', $spec_item_key);
            $spec_group_ids = GoodsSpecItemModel::whereIn('spec_item_id',$spec_item_key_ids)
                ->where('status',1)
                ->column('spec_group_id');
            $specList = GoodsSpecGroupModel::field('spec_group_id,spec_name')
                ->with(['item' => function($query) use ($spec_item_key_ids){
                    $query->whereIn('spec_item_id',$spec_item_key_ids);
                    $query->field('spec_item_id,spec_group_id,item_name');
                    $query->order('weigh','asc');
                    $query->where('status',1);
                }])
                ->whereIn('spec_group_id',$spec_group_ids)
                ->where('status',1)
                ->order('weigh','asc')
                ->select();
            $data->specList = $specList;

            // 是否可购买
            $system = model('app\common\model\SystemModel')->get(1);
            $data->isCanPay = true;
            if($system->is_burst_goods_buy_limit_user == 1) {
                if($data->is_index == 1) {
                    $data->isCanPay = false;
                }
                if($user) {
                    if($user->group_id > 1) {
                        $data->isCanPay = false;
                    }else{
//                        if($user->pid > 0) {
//                            $data->isCanPay = true;
//                        }
                        $user_relation = model('app\common\model\UserRelationModel')->get(['user_id' => $user_id]);
                        if($user_relation) {
                            if($user_relation->user_id_2 > 0) {
                                $data->isCanPay = true;
                            }else{
                                if($user_relation->user_id_3 > 0) {
                                    $data->isCanPay = true;
                                }
                            }
                        }
                    }
                }
            }

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 更新库存
     *
     * @param $goods_id
     * @param $goods_spec_id
     * @param $num
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function updateStock($goods_id,$goods_spec_id,$num): bool
    {
        $Goods = self::lock(true)->find($goods_id);
        $Goods->sales += $num;
//        $Goods->stock -= $num;
        $Goods->save();
        if (!empty($goods_spec_id)) {
            $GoodsSpec = GoodsSpecModel::lock(true)->find($goods_spec_id);
            if($GoodsSpec->spec_stock < $num){
                Exception("商品[ " .$Goods->goods_name . $GoodsSpec->spec_item_value ." ]商品规格库存不足", 43007);
            }
            $GoodsSpec->spec_stock -= $num;
            $GoodsSpec->spec_sold_count += $num;
            $GoodsSpec->save();
        }
        //商品库存自动上下架校验操作, 加入消息队列
        // 发布任务队列
        // 消息参数
        $queueParams = [
            'goods_id' => $goods_id,
            'goods_spec_id' => $goods_spec_id,
            'num' => $num,
        ];
        // 延时执行时间(秒)
        $queueTime = 0;
        $queue = 'jrbq';
        // 下单后未支付自动关闭订单操作
        Queue('app\common\job\OrderAfterAutoOper@GoodStockCheckOper', $queueParams, $queueTime, $queue);

        return true;
    }

    /**
     * 库存回滚
     *
     * @param $goods_id
     * @param $goods_spec_id
     * @param $num
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function stockRollback($goods_id,$goods_spec_id,$num): bool
    {
        $Goods = self::lock(true)->find($goods_id);
        $Goods->sales -= $num;
//        $Goods->stock += $num;
        $Goods->save();
        if (!empty($goods_spec_id)) {
            $GoodsSpec = GoodsSpecModel::lock(true)->find($goods_spec_id);
            $GoodsSpec->spec_stock += $num;
            $GoodsSpec->spec_sold_count -= $num;
            $GoodsSpec->save();
        }
        //商品库存自动上下架校验操作, 加入消息队列
        // 发布任务队列
        // 消息参数
        $queueParams = [
            'goods_id' => $goods_id,
            'goods_spec_id' => $goods_spec_id,
            'num' => $num,
        ];
        // 延时执行时间(秒)
        $queueTime = 0;
        $queue = 'yayiyun';
        // 下单后未支付自动关闭订单操作
        Queue('app\common\job\OrderAfterAutoOper@GoodStockCheckOper', $queueParams, $queueTime, $queue);

        return true;
    }


    public function spec(){
        return $this->hasMany('app\common\model\goods\GoodsSpecModel','goods_id','id');
    }

    public function spec1(){
        return $this->hasOne('app\common\model\goods\GoodsSpecModel','goods_id','id');
    }

    public function couponexchange(){
        return $this->belongsTo('app\common\model\CouponExchangeModel','coupon_exchange_id','id');
    }
}